
import os, sys, cv2, traceback
import numpy as np
parent_path = os.path.abspath(os.path.join(__file__, *(['..'] * 3)))
sys.path.insert(0, parent_path)

import time, threading, yaml, json
from flask import Flask, request
from core.server import Server, ServerResponse
from core.utils.logger import logging


app = Flask(__name__)


# 视频检测
def format_data_out_video(data):
    video_path = data["data"]["SteamReader_path"]
    # org
    save_path = "vis_" + os.path.basename(video_path)
    json_data = {
        "status": "OK" if data["code"] == 200 else "FAIL",
        "data": {
            # org
            video_path : save_path,
            # dev
            # video_path : data["save_path"],
            },
    }
    return json_data

# ------ 系统相关api ------

@app.route("/api/option/restart",methods=["get"])
def handle_restart():
    try:
        server.restart()
        return {"code":200}
    except Exception as e:
        logging.error(traceback.format_exc())

# ------ 功能api ------
test_flag = True


@app.route("/all_detect",methods=["post"])
def handle_all_detect():
    """加载所有模型,检测所有类型
    """
    logging.info(f"|all_detect|")
    databox = {}
    try:
        code = 200
        message = ""
        json_data = request.json
        json_data = format_data_in(json_data)
        databox = server.main_request(data=json_data)
        # json_data["data"]["data"]["tag"] = "pop"
        # server.main_request(data=json_data)
    except Exception as e:
        code = 500
        message = traceback.format_exc()
        logging.error(message)
    response = ServerResponse(
        id=databox["id"] if "id" in databox else None,
        code=code,
        message=message,
        data = databox)
    response = objectdetect_format_data_out(response)
    logging.info("task id {} response".format(json_data["id"]))
    return response

@app.route("/api/main",methods=["post"])
def handle_main():
    """
    data: {
        id: 1 # 流水号
        tag: task # 1级请求
        data: {
            tag: # rooftop 2级请求
            data: "b64_data..."
        }
    }
    """
    try:
        logging.info(f"|detect, json data: {request.json}|")
        json_data = request.json
        databox, message = server.main_request(json_data)
        response = {"message":message}
        return response
    except Exception as e:
        logging.error(traceback.format_exc())


if __name__ == '__main__':

    # 日志初始化
    log_path = "core/utils/logger_samples/log_cfg.yaml"
    logging.set_config(log_path)

    # 定义后台服务类
    server_cfg_path = os.path.dirname(__file__)+"/configs/server_cfg.yml"
    server = Server(server_cfg_path)
    logging.info("|server start|")
    app.run(host="0.0.0.0",port=2674,threaded=True)
    logging.info("|server stop|")

